$(document).ready(function() {
    addPost.init();
});

var addPost = (function() {

    function addNewPost() {
        var title = $('#postTitle').val();    
        
        $('.form-group').removeClass('has-error');
        $('.errorHandler').html('');
        if (!title) {
            $('#postTitle').parents('.form-group').addClass('has-error');
            $('#addNewPost').find('i.fa').attr('class', 'fa fa-plus-circle');
            return false;
        }
        
        var lstProfile = "";
        for(var i in $("#demo3").tagit("tags"))
            lstProfile += $("#demo3").tagit("tags")[i].value + ",";
        $('#demo3Out').html('<input type="hidden" id="postListProfile" name="postListProfile" value="' + lstProfile + '" />');
        
        $('#postContent').val(tinyMCE.activeEditor.getContent());
        $('#appInput').ajaxSubmit({
            url: '/post/ajax-add',
            type: 'post',
            dataType: 'json',
            timeout: 3000,
            success: function(resp) {
                if (resp.err === 0) {//chuyen trang                    
                    window.location.href = '/post/edit?id=' + resp.data.id + '&pid=' + resp.data.pid + '#msg=' + resp.msg;
                } else {                   
                    $('.errorHandler').removeClass('text-success').addClass('text-danger').html(resp.msg).show();
                    $('#saveNewPost').find('i').attr('class', 'fa fa-plus-circle');
                }
            }
        });                
    }

    function initHanlder() {
        initWysiwyg();

        $('#addPost').click(function() {
            $(this).find('i.fa').attr('class', 'fa fa-spinner fa-spin');
            addNewPost();
            return false;
        });
    }
    return {
        init: function() {
            initHanlder();
            initDatePicker('#postTime');
        }
    };
})();